﻿using System;
using System.Web.UI;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using System.ComponentModel;

namespace Marbles.Core.Controls
{
    [ToolboxData("<{0}:ModalDialog runat=server></{0}:ModalDialog>")]
    public class ModalPopup : Panel
    {

        [Category("Appearance")]
        public string Title
        {
            get { object obj = ViewState["title"]; return (obj == null) ? "" : obj.ToString(); }
            set { ViewState["title"] = value; }
        }



        protected override void Render(HtmlTextWriter writer)
        {
            base.Render(writer);
            writer.Write("<script language=\"javascript\" type=\"text/javascript\">");
            writer.Write(GetScript());
            writer.Write("</script>");
        }

        public bool IsModal { get { object obj = ViewState["IsModal"]; return (obj == null) ? true : Convert.ToBoolean(obj); } set { ViewState["IsModal"] = value; } }

        private string GetScript()
        {
            StringBuilder sb = new StringBuilder();
            string param = string.Empty;

            sb.AppendLine("$(function() {");
            sb.AppendLine("$(\"#" + this.ClientID + "\").dialog(\"destroy\");");

            sb.Append("$( \"#" + this.ClientID + "\" ).dialog({");

            if (!this.Height.IsEmpty)
            {
                if (!string.IsNullOrEmpty(param)) { param += ", "; }
                param += "height:" + this.Height.Value.ToString();
            }

            if (!this.Width.IsEmpty)
            {
                if (!string.IsNullOrEmpty(param)) { param += ", "; }
                param += "width:" + this.Width.Value.ToString();
            }

            if (!string.IsNullOrEmpty(param)) { param += ", "; }
            param += "title: '" + this.Title + "'";

            if (!string.IsNullOrEmpty(param)) { param += ", "; }
            param += "closeOnEscape: false";

            if (!string.IsNullOrEmpty(param)) { param += ", "; }
            param += "modal: " + IsModal.ToString().ToLower();

            sb.Append(param);
            sb.AppendLine("});");
            sb.Append("$( \"#" + this.ClientID + "\" ).parent().appendTo($(\"form:first\"));");
            sb.AppendLine("});");

            return sb.ToString();
        }

    }
}
